// 内容脚本 - 处理页面交互
class TranslationUI {
  constructor() {
    this.popup = null;
    this.isVisible = false;
    this.autoTranslate = true;
    this.settings = {};
    this.init();
  }

  async init() {
    try {
      await this.loadSettings();
      this.createPopup();
      this.bindEvents();
    } catch (error) {
      console.error('TranslationUI init error:', error);
      // 如果初始化失败，尝试重新初始化
      setTimeout(() => {
        this.init();
      }, 1000);
    }
  }

  async loadSettings() {
    try {
      // 检查扩展是否仍然有效
      if (!chrome.runtime?.id) {
        console.warn('Extension context invalidated, using default settings');
        this.settings = { autoTranslate: true };
        this.autoTranslate = true;
        return;
      }

      const response = await chrome.runtime.sendMessage({ type: 'getSettings' });
      if (response && response.error) {
        console.warn('Failed to load settings:', response.error);
        this.settings = { autoTranslate: true };
        this.autoTranslate = true;
      } else {
        this.settings = response || { autoTranslate: true };
        this.autoTranslate = response?.autoTranslate !== false;
      }
    } catch (error) {
      console.error('Failed to load settings:', error);
      this.settings = { autoTranslate: true };
      this.autoTranslate = true;
    }
  }

  createPopup() {
    this.popup = document.createElement('div');
    this.popup.id = 'translation-popup';
    this.popup.innerHTML = `
      <div class="translation-header">
        <span class="translation-title">翻译结果</span>
        <div class="translation-actions">
          <button class="favorite-btn" title="收藏">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/>
            </svg>
          </button>
          <button class="copy-btn" title="复制译文">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>
              <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>
            </svg>
          </button>
          <button class="close-btn" title="关闭">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <line x1="18" y1="6" x2="6" y2="18"></line>
              <line x1="6" y1="6" x2="18" y2="18"></line>
            </svg>
          </button>
        </div>
      </div>
      <div class="translation-content">
        <div class="original-text"></div>
        <div class="translated-text"></div>
        <div class="translation-info">
          <span class="service-name"></span>
          <span class="translation-time"></span>
        </div>
      </div>
    `;
    
    document.body.appendChild(this.popup);
  }

  bindEvents() {
    // 监听选中文本事件
    document.addEventListener('mouseup', this.handleTextSelection.bind(this));
    
    // 监听点击事件，隐藏弹窗
    document.addEventListener('click', (e) => {
      if (!this.popup.contains(e.target)) {
        this.hide();
      }
    });

    // 绑定弹窗内的事件
    this.popup.querySelector('.favorite-btn').addEventListener('click', this.toggleFavorite.bind(this));
    this.popup.querySelector('.copy-btn').addEventListener('click', this.copyTranslation.bind(this));
    this.popup.querySelector('.close-btn').addEventListener('click', this.hide.bind(this));

    // 监听来自background的消息
    chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
      try {
        if (request.type === 'showTranslation') {
          this.showTranslation(request.data);
        }
      } catch (error) {
        console.error('Content script message listener error:', error);
      }
    });
  }

  async handleTextSelection(e) {
    if (!this.autoTranslate) return;

    const selection = window.getSelection();
    const selectedText = selection.toString().trim();

    if (selectedText && selectedText.length > 0 && selectedText.length < 500) {
      // 延迟一下，避免频繁请求
      clearTimeout(this.selectionTimeout);
      this.selectionTimeout = setTimeout(async () => {
        await this.translateText(selectedText, e);
      }, 300);
    }
  }

  async translateText(text, event) {
    try {
      // 检查扩展是否仍然有效
      if (!chrome.runtime?.id) {
        this.showError('扩展已失效，请重新加载扩展');
        return;
      }

      const response = await chrome.runtime.sendMessage({
        type: 'translate',
        text: text,
        fromLang: 'auto',
        toLang: 'zh'
      });

      if (response && response.error) {
        this.showError(response.error);
      } else if (response) {
        this.showTranslation(response, event);
      } else {
        this.showError('翻译失败: 无响应');
      }
    } catch (error) {
      console.error('Content script translation error:', error);
      if (error.message.includes('Extension context invalidated')) {
        this.showError('扩展已失效，请重新加载扩展');
      } else {
        this.showError('翻译失败: ' + error.message);
      }
    }
  }

  showTranslation(data, event) {
    const originalTextEl = this.popup.querySelector('.original-text');
    const translatedTextEl = this.popup.querySelector('.translated-text');
    const serviceNameEl = this.popup.querySelector('.service-name');
    const timeEl = this.popup.querySelector('.translation-time');

    originalTextEl.textContent = data.originalText;
    translatedTextEl.textContent = data.translatedText;
    serviceNameEl.textContent = this.getServiceDisplayName(data.service);
    timeEl.textContent = new Date().toLocaleTimeString();

    // 检查是否已收藏
    this.updateFavoriteButton(data);

    // 定位弹窗
    this.positionPopup(event);

    this.show();
  }

  showError(message) {
    const originalTextEl = this.popup.querySelector('.original-text');
    const translatedTextEl = this.popup.querySelector('.translated-text');
    
    originalTextEl.textContent = '翻译失败';
    
    // 如果是扩展失效错误，显示重新加载按钮
    if (message.includes('扩展已失效')) {
      translatedTextEl.innerHTML = `
        ${message}
        <br><br>
        <button id="reload-extension" style="
          background: #2196F3;
          color: white;
          border: none;
          padding: 4px 8px;
          border-radius: 4px;
          cursor: pointer;
          font-size: 12px;
        ">重新加载扩展</button>
      `;
      
      // 绑定重新加载按钮事件
      setTimeout(() => {
        const reloadBtn = this.popup.querySelector('#reload-extension');
        if (reloadBtn) {
          reloadBtn.addEventListener('click', () => {
            chrome.runtime.reload();
          });
        }
      }, 100);
    } else {
      translatedTextEl.textContent = message;
    }
    
    this.show();
  }

  positionPopup(event) {
    const rect = this.popup.getBoundingClientRect();
    const viewportWidth = window.innerWidth;
    const viewportHeight = window.innerHeight;

    let x = event ? event.clientX : 100;
    let y = event ? event.clientY + 20 : 100;

    // 确保弹窗不超出视口边界
    if (x + rect.width > viewportWidth) {
      x = viewportWidth - rect.width - 10;
    }
    if (y + rect.height > viewportHeight) {
      y = event.clientY - rect.height - 10;
    }

    this.popup.style.left = x + 'px';
    this.popup.style.top = y + 'px';
  }

  show() {
    this.popup.style.display = 'block';
    this.isVisible = true;
  }

  hide() {
    this.popup.style.display = 'none';
    this.isVisible = false;
  }

  async toggleFavorite() {
    const originalText = this.popup.querySelector('.original-text').textContent;
    const translatedText = this.popup.querySelector('.translated-text').textContent;
    
    if (originalText === '翻译失败') return;

    const data = {
      originalText: originalText,
      translatedText: translatedText,
      service: this.getCurrentService(),
      timestamp: Date.now()
    };

    try {
      const response = await chrome.runtime.sendMessage({
        type: 'saveFavorite',
        data: data
      });

      this.updateFavoriteButton(data, true);
    } catch (error) {
      console.error('收藏失败:', error);
    }
  }

  updateFavoriteButton(data, isFavorited = false) {
    const favoriteBtn = this.popup.querySelector('.favorite-btn');
    const svg = favoriteBtn.querySelector('svg');
    
    if (isFavorited) {
      svg.style.fill = '#ffd700';
      favoriteBtn.title = '已收藏';
    } else {
      svg.style.fill = 'none';
      favoriteBtn.title = '收藏';
    }
  }

  async copyTranslation() {
    const translatedText = this.popup.querySelector('.translated-text').textContent;
    
    try {
      await navigator.clipboard.writeText(translatedText);
      this.showCopySuccess();
    } catch (error) {
      // 降级方案
      const textArea = document.createElement('textarea');
      textArea.value = translatedText;
      document.body.appendChild(textArea);
      textArea.select();
      document.execCommand('copy');
      document.body.removeChild(textArea);
      this.showCopySuccess();
    }
  }

  showCopySuccess() {
    const copyBtn = this.popup.querySelector('.copy-btn');
    const originalTitle = copyBtn.title;
    copyBtn.title = '已复制';
    copyBtn.style.color = '#4CAF50';
    
    setTimeout(() => {
      copyBtn.title = originalTitle;
      copyBtn.style.color = '';
    }, 1000);
  }

  getServiceDisplayName(service) {
    const serviceNames = {
      'baidu': '百度翻译',
      'chrome': 'Chrome翻译',
      'tencent': '腾讯翻译君',
      'google': 'Google翻译',
      'deepl': 'DeepL翻译',
      'bing': 'Bing翻译',
      'youdao': '有道词典'
    };
    return serviceNames[service] || service;
  }

  getCurrentService() {
    return this.settings.currentAPI || 'bing';
  }
}

// 初始化翻译UI
const translationUI = new TranslationUI(); 